package tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName LeftLeafSum
 * @Description TODO
 * @Author lenovo
 * @Date 2023-03-14 19:25
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class LeftLeafSum {
    /**
     * 首先要注意是判断左叶子，不是二叉树左侧节点，所以不要上来想着层序遍历。
     * <p>
     * 因为题目中其实没有说清楚左叶子究竟是什么节点，那么我来给出左叶子的明确定义：节点A的左孩子不为空，且左孩子的左右孩子都为空（说明是叶子节点），那么A节点的左孩子为左叶子节点
     */


    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        int left = sumOfLeftLeaves(root.left);
        int right = sumOfLeftLeaves(root.right);
        int mid = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            mid = root.left.val;
        }

        return left + right + mid;
    }


    public int sumOfLeftLeaves1(TreeNode root) {

        if (root == null) return 0;

        Queue<TreeNode> queue = new LinkedList<>();

        queue.add(root);
        int sum = 0;
        while (!queue.isEmpty()) {

            int size = queue.size();

            while (size > 0) {
                TreeNode poll = queue.poll();

                if (poll.left != null) queue.add(poll.left);

                if (poll.left != null && poll.left.left == null && poll.left.right == null)
                    sum += poll.left.val;

                if (poll.right != null) queue.add(poll.right);
                size--;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(2);

        TreeNode treeNode1 = new TreeNode(3);


        TreeNode treeNode2 = new TreeNode(4);

        TreeNode treeNode3 = new TreeNode(5);
        treeNode.left = treeNode1;
        treeNode.right = treeNode2;
        treeNode2.left = treeNode3;
        LeftLeafSum leftLeafSum = new LeftLeafSum();
        int i = leftLeafSum.sumOfLeftLeaves1(treeNode);
        System.out.println(i);

    }
}